﻿using System;
using System.Globalization;
using System.Text;

namespace SBToolkit.Text
{
    /// <summary>
    /// Extends <see cref="String"/> with additional features.
    /// </summary>
    public static class StringHelper
    {
        /// <summary>
        /// Takes specified <paramref name="length"/> substring starting form the left.
        /// </summary>
        /// <param name="s">The string.</param>
        /// <param name="length">Subtring length.</param>
        /// <returns>Left part of the specified string.</returns>
        public static string Left(this string s, int length)
        {
            if (!String.IsNullOrEmpty(s) && s.Length >= length)
            {
                return s.Substring(0, length);
            }
            
            return s;
        }

        /// <summary>
        /// Takes specified <paramref name="length"/> subtring starting from the right.
        /// </summary>
        /// <param name="s">The string.</param>
        /// <param name="length">Subtring length.</param>
        /// <returns>Right part of the specified string.</returns>
        public static string Right(this string s, int length)
        {
            if (!String.IsNullOrEmpty(s) && s.Length >= length)
            {
                return s.Substring(s.Length - length);
            }

            return s;
        }

        /// <summary>
        /// Reverses string.
        /// </summary>
        /// <param name="s">The string.</param>
        /// <returns>Reversed string.</returns>
        public static string Reverse(this string s)
        {
            char[] charArray = s.ToCharArray();
            Array.Reverse(charArray);
            return new string(charArray);
        }

        /// <summary>
        /// True when string is null or String.Empty.
        /// </summary>
        /// <param name="s">The string.</param>
        /// <returns><c>true</c> if string is NULL or empty; otherwise <c>false</c>.</returns>
        public static bool IsNullOrEmpty(this string s)
        {
            return string.IsNullOrEmpty(s);
        }

        /// <summary>
        /// Removes all accent marks from the specified string.
        /// </summary>
        /// <param name="s">The string.</param>
        /// <returns>The string without accent marks.</returns>
        public static string RemoveAccents(this string s)
        {
            var sb = new StringBuilder(s.Normalize(NormalizationForm.FormKD));
            for (int i = 0; i < sb.Length; i++)
            {
                if (CharUnicodeInfo.GetUnicodeCategory(sb[i]) == UnicodeCategory.NonSpacingMark)
                {
                    sb.Remove(i, 1);
                }
            }

            return sb.ToString();
        }
    }
}